package org.codert.jpa.config;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author: TanJingyu
 * @create: 2021-09-21 13:10
 **/
//@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object advice(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
//        for (ObjectError error : allErrors) {
//            //
//        }
        return allErrors.get(0).getDefaultMessage();
    }

    @ExceptionHandler(Exception.class)
    public Object advice(Exception e) {
        return e.getMessage();
    }
}
